package com.zjzywl.iotSendthings.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zjzywl.iotSendthings.entity.CPicture;
import com.zjzywl.iotSendthings.repository.CPictureRepository;
import com.zjzywl.iotSendthings.util.WebResult;
/*
 * 物品拍照
 */
@RestController
@RequestMapping(value="/picture")
public class CPictureController extends BaseController  {
	
	@Autowired
	private CPictureRepository repository;
	
	 @PutMapping("/upload")
	 public WebResult uploadImg(@RequestParam("picture") MultipartFile multipartFile)  {
	        if (multipartFile.isEmpty() || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
	           return WebResult.FAIL("图片数据为空！");
	        }
	        String contentType = multipartFile.getContentType();
	        if (!contentType.contains("")) {
	        	return WebResult.FAIL("文件类型为空！");
	        }
	        String root_fileName = multipartFile.getOriginalFilename();
	        logger.info( root_fileName+contentType);

	        String file_name = null;
	        try {
	            file_name = saveImg(multipartFile,"picture",root_fileName);

	            if(StringUtils.isNotBlank(file_name)){
	            	//保存照片数据
	            	CPicture cp = new CPicture();
	            	String uuid = getFilenameExcludeExpandedname(root_fileName);
	            	cp.setUuid(uuid);
	            	cp.setFile("picture\\"+root_fileName);
	            	repository.save(cp);
	            	
	            	return WebResult.OK(file_name);
	            }

	        } catch (IOException e) {
	        	return WebResult.FAIL(e.getMessage());
	        }
	        return WebResult.FAIL("接收图片失败！");
	    }
	 
	 
	 
	 
	 @RequestMapping(value = "/getImg", method = RequestMethod.GET)
		public void  doGetBackgroundImg(String uuid,HttpServletResponse response) throws Exception {	

		 	CPicture cp = repository.findByUuid(uuid);
			
			String pictureFile = cp.getFile();
			 //MagicMatch match = Magic.getMagicMatch(new File(pictureFile),false);
			 //response.setContentType(match.getMimeType());  
			 response.setContentType("image/jpeg ");
			 FileInputStream fis = new FileInputStream(pictureFile);
			
			 OutputStream os=response.getOutputStream();		  
			 try
			 {
				  int count = 0;
				  byte[] buffer = new byte[1024 * 1024];

				  
				  while ((count = fis.read(buffer)) != -1){
					  os.write(buffer, 0, count);		  
				  }		  

				  os.flush();
			 }
			 catch (Exception e)
			 {
				logger.error("获取图片出错", e);
			 }
			 finally
			 {
			  if (os != null)
			   os.close();
			  if (fis != null)
			   fis.close();
			 }
		}
	 
	 @GetMapping(value="/data")
	 public WebResult getPicture(@PathParam("uuid") String uuid) {
		 CPicture cp = repository.findByUuid(uuid);
		 if(cp==null) {
			 return WebResult.FAIL("找不到该图片");
		 } else {
			 return WebResult.OK(cp);
		 }
	 }
	 
	    /**
	     * 保存文件，直接以multipartFile形式
	     * @param multipartFile
	     * @param path 文件保存绝对路径
	     * @return 返回文件名
	     * @throws IOException
	     */
	    private static String saveImg(MultipartFile multipartFile,String path,String name) throws IOException {
	        File file = new File(path);
	        if (!file.exists()) {
	            file.mkdirs();
	        }
	        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
	        String fileName = name;
	        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
	        byte[] bs = new byte[1024];
	        int len;
	        while ((len = fileInputStream.read(bs)) != -1) {
	            bos.write(bs, 0, len);
	        }
	        bos.flush();
	        bos.close();
	        return fileName;
	    }
	    
	    private String getFilenameExcludeExpandedname(String filename) {
	    	String name = filename.substring(0, filename.indexOf('.'));
	    	return name;
	    }
	    
	    
}
